<template>
  <div class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
    >
      <van-cell
        v-for="(item, index) in list"
        :key="item.art_id + index"
        :title="item.title"
      />
    </van-list>
  </div>
</template>

<script>
import {getSearch} from '@/api/search'

export default {
  props: ['searchText'],
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      error: false
    }
  },
  methods: {
    async onLoad () {
      try {
        if(Math.random() > 0.9) {
          throw new Error('出错了')
        }

        const {data: {data: {results, total_count}}} = await getSearch({
          page: this.page,
          per_page: 20,
          q: this.searchText
        })

        this.list = [...this.list, ...results]

        this.loading = false
        this.page += 1

        if(this.list.length >= total_count) {
          this.finished = true
        }
      } catch(err) {
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="less"></style>
